package com.example.myapplication.function.musicmode

/**
 * 1. 实时音频预处理类
 */
class AudioNoiseFilter {
    
    companion object {
        private const val NOISE_THRESHOLD = 0.02f // 噪音阈值
        private const val SILENCE_THRESHOLD = 0.001f // 静音阈值
        private const val SMOOTHING_FACTOR = 0.7f // 平滑因子
    }
    
    /**
     * 实时噪音过滤
     */
    fun filterNoiseRealTime(audioData: FloatArray): FloatArray {
        val filteredData = audioData.copyOf()
        
        // 1. 计算音频能量
        val energy = calculateEnergy(audioData)
        
        // 2. 如果能量低于静音阈值，返回静音
        if (energy < SILENCE_THRESHOLD) {
            return FloatArray(audioData.size) { 0f }
        }
        
        // 3. 应用噪音门限
        applyNoiseGate(filteredData, energy)
        
        // 4. 应用平滑滤波
        applySmoothing(filteredData)
        
        // 5. 应用高通滤波器（去除低频噪音）
        applyHighPassFilter(filteredData)
        
        return filteredData
    }
    
    /**
     * 计算音频能量
     */
    private fun calculateEnergy(audioData: FloatArray): Float {
        var sum = 0f
        for (sample in audioData) {
            sum += sample * sample
        }
        return sum / audioData.size
    }
    
    /**
     * 应用噪音门限
     */
    private fun applyNoiseGate(audioData: FloatArray, energy: Float) {
        if (energy < NOISE_THRESHOLD) {
            // 低于阈值，认为是噪音，进行衰减
            val attenuation = energy / NOISE_THRESHOLD
            for (i in audioData.indices) {
                audioData[i] *= attenuation
            }
        }
    }
    
    /**
     * 应用平滑滤波（移动平均）
     */
    private fun applySmoothing(audioData: FloatArray) {
        if (audioData.size < 3) return
        
        val windowSize = 3
        val smoothed = FloatArray(audioData.size)
        
        for (i in audioData.indices) {
            var sum = 0f
            var count = 0
            
            for (j in -windowSize/2..windowSize/2) {
                val index = i + j
                if (index in audioData.indices) {
                    sum += audioData[index]
                    count++
                }
            }
            
            smoothed[i] = sum / count
        }
        
        // 应用平滑结果
        for (i in audioData.indices) {
            audioData[i] = SMOOTHING_FACTOR * smoothed[i] + (1 - SMOOTHING_FACTOR) * audioData[i]
        }
    }
    
    /**
     * 应用简单的高通滤波器
     */
    private fun applyHighPassFilter(audioData: FloatArray) {
        if (audioData.size < 2) return
        
        val alpha = 0.95f // 高通滤波系数
        var prevOutput = 0f
        
        for (i in audioData.indices) {
            val output = alpha * prevOutput + alpha * (audioData[i] - audioData.getOrElse(i-1) { 0f })
            prevOutput = output
            audioData[i] = output
        }
    }
    
    /**
     * 频谱噪音抑制（更高级的降噪）
     */
    fun spectralNoiseReduction(audioData: FloatArray): FloatArray {
        // 这里可以实现更复杂的频域降噪算法
        // 例如使用FFT进行频谱分析，然后抑制噪音频段
        
        // 简化的实现：使用带通滤波器保留人声频段 (80Hz - 1000Hz)
        return applyBandPassFilter(audioData, 80f, 1000f, 44100f)
    }
    
    /**
     * 简单的带通滤波器实现
     */
    fun applyBandPassFilter(
        audioData: FloatArray, 
        lowFreq: Float, 
        highFreq: Float, 
        sampleRate: Float
    ): FloatArray {
        val filtered = audioData.copyOf()
        
        // 简化的IIR带通滤波器实现
        val dt = 1.0f / sampleRate
        val rcLow = 1.0f / (2 * Math.PI.toFloat() * lowFreq)
        val rcHigh = 1.0f / (2 * Math.PI.toFloat() * highFreq)
        val alphaLow = dt / (rcLow + dt)
        val alphaHigh = rcHigh / (rcHigh + dt)
        
        var prevLow = 0f
        var prevHigh = 0f
        
        for (i in filtered.indices) {
            // 高通部分
            val highPass = alphaHigh * (prevHigh + filtered[i] - (if (i > 0) filtered[i-1] else 0f))
            prevHigh = highPass
            
            // 低通部分
            val lowPass = prevLow + alphaLow * (highPass - prevLow)
            prevLow = lowPass
            
            filtered[i] = lowPass
        }
        
        return filtered
    }
}